package com.xzit.headline.fragment.sub;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.j256.ormlite.dao.Dao;
import com.xzit.headline.R;
import com.xzit.headline.activity.DetailActivity;
import com.xzit.headline.adapter.NewListAdapter;
import com.xzit.headline.bean.MoreData;
import com.xzit.headline.bean.NewListData;
import com.xzit.headline.db.MyDbHelper;
import com.xzit.headline.db.NewInfo;
import com.xzit.headline.fragment.BaseFragment;
import com.xzit.headline.net.MyApi;

import java.sql.SQLException;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

//1.继承BaseFragment,新闻列表展示页碎片
public class NewListFragment extends BaseFragment {
    //10.3 定义一个变量保存下一页的url地址
    private String loadMoreUrl = null;

    private String loadFirstUrl = null;

    public NewListFragment(String loadFirstUrl) {
        this.loadFirstUrl = loadFirstUrl;
    }

    //2.重写getMyView
    //3.布局列表
    @Override
    public View getMyView() {
        //加载
        return View.inflate(getContext(), R.layout.fragment_new_list, null);
    }

    //5.请求服务端数据
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        //#

        //6.执行请求
        retrofit.create(MyApi.class).getNewList(loadFirstUrl).enqueue(new Callback<NewListData>() {
            @Override
            public void onResponse(Call<NewListData> call, Response<NewListData> response) {
                /*System.out.println(response.body().retcode);
                System.out.println(response.body().data);*/
                setDataToView(response.body().data);

                //10.4保存下一页地址
                loadMoreUrl = response.body().data.more;
            }

            @Override
            public void onFailure(Call<NewListData> call, Throwable t) {

            }
        });
    }

    //7.显示
    private NewListAdapter adapter;
    private PullToRefreshListView pullToRefreshListView;


    //10.下拉刷新与滚动加载
    private void setDataToView(NewListData.DataBean data) {
        //7.1查找控件
        //10.1判断控件是否为空
        if (pullToRefreshListView == null) {
            pullToRefreshListView = fragmentView.findViewById(R.id.pull_listView);

            //监听点击
            onListeners(pullToRefreshListView);

            //10.2 给列表添加滚动加载与下拉刷新监听器
            onListenersPull(pullToRefreshListView);

            //7.2配置一个适配器
            adapter = new NewListAdapter(data.news, getContext());

            //关联适配器
            pullToRefreshListView.setAdapter(adapter);
        } else {
            //第二次请求服务端
        }

    }

    private void onListenersPull(PullToRefreshListView pullToRefreshListView) {
        //10.3设置刷新的模式为BOTH
        pullToRefreshListView.setMode(PullToRefreshBase.Mode.BOTH);
        pullToRefreshListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(final PullToRefreshBase<ListView> refreshView) {
                //下拉
                retrofit.create(MyApi.class).getNewList(loadFirstUrl).enqueue(new Callback<NewListData>() {
                    @Override
                    public void onResponse(Call<NewListData> call, Response<NewListData> response) {
                        //10.5保存下一页地址
                        loadMoreUrl = response.body().data.more;

                        //请求成功
                        //1,请求到服务端数据之后,先清空集合,再添加数据,再刷新列表,关闭等待
                        if (adapter != null) {
                            adapter.getListData().clear();//清空
                            List<NewListData.DataBean.NewsBean> newsBeanList = response.body().data.news;
                            adapter.getListData().addAll(newsBeanList);//添加数据,多个元素要加入到当前集合使用addAll

                            adapter.notifyDataSetChanged();//整体刷新

                            refreshView.onRefreshComplete();//关闭等待视图
                            Toast.makeText(getContext(), "下拉刷新成功", Toast.LENGTH_SHORT).show();
                        }

                    }

                    @Override
                    public void onFailure(Call<NewListData> call, Throwable t) {
                        Toast.makeText(getContext(), "请求失败", Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void onPullUpToRefresh(final PullToRefreshBase<ListView> refreshView) {
                //滚动加载需要使用loadMoreUrl地址获取下一页数据
                retrofit.create(MyApi.class).getMoreData(loadMoreUrl).enqueue(new Callback<MoreData>() {
                    @Override
                    public void onResponse(Call<MoreData> call, Response<MoreData> response) {
                        //1.不清空集合
                        if (adapter != null) {
                            //2.直接添加到当前集合
                            adapter.getListData().addAll(response.body().data.news);
                            //刷新列表,关闭等待
                            adapter.notifyDataSetChanged();
                            refreshView.onRefreshComplete();
                        }
                        Toast.makeText(getContext(), "请求成功", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onFailure(Call<MoreData> call, Throwable t) {
                        Toast.makeText(getContext(), "请求失败", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }

    //9.监听点击
    private void onListeners(PullToRefreshListView pullToRefreshListView) {
        //9.1点击监听器
        pullToRefreshListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                // int position当前点击的位置
                NewListData.DataBean.NewsBean bean = adapter.getListData().get(position - 1);
                //Toast.makeText(getContext(), "id="+bean.id, Toast.LENGTH_SHORT).show();

                //列表页面跳转到详情页面
                goToNewDetailsPage(bean);

                //9.2使用数据库保存起来
                MyDbHelper helper = new MyDbHelper(getContext());
                try {
                    //dao是有增删改查的对象
                    Dao<NewInfo, Integer> dao = helper.getDao(NewInfo.class);
                    //保存
                    List<NewInfo> list = dao.queryForEq("newId", bean.id);//select语句
                    if (list == null || list.size() == 0) {
                        dao.create(new NewInfo(bean.id));//执行一条insert语句
                    }

                    List<NewInfo> newInfos = dao.queryForAll();
                    System.out.println(newInfos);

                    //9.6 调用getView刷新列表一行，如果需要刷新整个表，调adapter.notifyDataSetChanged()
                    adapter.notifyDataSetChanged();


                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void goToNewDetailsPage(NewListData.DataBean.NewsBean bean) {
        //1.打开页面
        Intent intent = new Intent(getContext(), DetailActivity.class);

        intent.putExtra("bean", bean);//需要对象的类实现序列化

        //2.传递参数
        getActivity().startActivity(intent);

        //3.收藏
    }
}
